package controllers

import (
	"TTSX_beego/models"
	"TTSX_beego/torch"
	"encoding/base64"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
	"regexp"
	"strconv"
)

type UserController struct {
	beego.Controller
}

func (This UserController) LogOut() {
	This.DelSession("userName")
	This.Ctx.Redirect(302, "/login")
}

//显示注册页面
func (This *UserController) ShowReg() {
	This.TplName = "register.html"
}

//注册请求
func (This *UserController) HandleReg() {
	userName := This.GetString("user_name")
	pwd := This.GetString("pwd")
	cpwd := This.GetString("cpwd")
	email := This.GetString("email")

	if !torch.All(userName, pwd, cpwd, email) { //数据不唯一
		This.Data["errmsg"] = "数据不完整"
		This.TplName = "register.html"
		return
	}

	if pwd != cpwd {
		This.Data["errmsg"] = "用户名密码不一致"
		This.TplName = "register.html"
		return
	} //密码不一致

	reg, _ := regexp.Compile("^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-z0-9_-]+(\\.[a-zA-z0-9_-]+)+$")
	res := reg.FindString(email)
	if res == "" {
		This.Data["errmsg"] = "邮箱格式错误"
		This.TplName = "register.html"
		return
	}

	o := orm.NewOrm()
	user := models.User{Name: userName, PassWord: pwd, Email: email}
	_, err := o.Insert(&user)
	if err != nil {
		This.Data["errmsg"] = "注册失败,用户名或密码错误"
		This.TplName = "register.html"
		return
	}

	//发送邮件
	//go func() {
	//	emailConfig := `{"username"}`
	//	emailConn := utils.NewEMail(emailConfig)
	//	emailConn.From = "title"
	//	emailConn.To = []string{email}
	//	emailConn.Subject = "注册"
	//	emailConn.Text = fmt.Sprintf("127.0.0.1:8080/active?id=%d", user.Id)
	//}()

	This.Ctx.WriteString("注册成功，请激活用户")

}

func (This *UserController) ActiveUser() {
	id, err := This.GetInt("id")
	if err != nil {
		This.Data["errmsg"] = "用户不存在"
		This.TplName = "register.html"
		return
	}

	o := orm.NewOrm()
	user := models.User{Id: id}
	err = o.Read(&user)
	if err != nil {
		This.Ctx.WriteString("用户id不存在")
		return
	}

	user.Active = true

	o.Update(&user)

	This.Redirect("/login", 302)

}

func (This *UserController) ShowLogin() {
	userName := This.Ctx.GetCookie("userName")
	temp, err := base64.StdEncoding.DecodeString(userName)
	if err != nil {
		userName = ""
		beego.Info(err)
	} else {
		userName = string(temp)
	}
	This.Data["userName"] = userName
	This.TplName = "login.html"
}

func (This UserController) HandleLog() {
	userName := This.GetString("username")
	Pwd := This.GetString("pwd")
	check := This.GetString("check")
	if !torch.All(userName, Pwd) {
		This.Data["errmsg"] = "数据不完整"
		This.TplName = "login.html"
		return
	}

	//判断登入数据
	o := orm.NewOrm()
	user := models.User{Name: userName}
	err := o.Read(&user, "Name")
	if err != nil {
		beego.Info("err", err)
		This.Data["errmsg"] = "用户名与密码不匹配"
		This.TplName = "login.html"
		return
	}

	if Pwd != user.PassWord {
		This.Data["errmsg"] = "用户名与密码不匹配"
		This.TplName = "login.html"
		return
	}

	if user.Active != true {
		This.Data["errmsg"] = "用户未激活，请激活"
		This.TplName = "login.html"
		return
	}

	if check == "on" {
		temp := base64.StdEncoding.EncodeToString([]byte(userName))
		This.Ctx.SetCookie("userName", temp, 12*24*3600)
	} else {
		This.Ctx.SetCookie("userName", userName, -1)
	}
	This.SetSession("userName", userName)

	This.Ctx.Redirect(302, "/")

}

func GetUser(This *UserController) string {
	userName := This.GetSession("userName")
	This.Data["userName"] = userName
	if userName == nil {
		This.Data["userName"] = ""
	} else {
		This.Data["userName"] = userName.(string)
	}
	return userName.(string)

}

func (This *UserController) UserInfo() {

	userName := GetUser(This)

	var addr models.Address
	o := orm.NewOrm()
	o.QueryTable("Address").RelatedSel("User").
		Filter("User__Name", userName).Filter("Isdefault", true).One(&addr)
	if addr.Id == 0 {
		This.Data["addr"] = ""
	} else {
		This.Data["addr"] = addr
	}

	//添加最近访问
	var user models.User
	user.Name = userName
	o.Read(&user, "Name")

	var goods []models.GoodsSKU

	conn, err := redis.Dial("tcp", "192.168.88.137:6379")

	if err != nil {
		beego.Info("链接错误", err)
	} else {
		rep, _ := redis.Ints(conn.Do("lrange", "history_"+strconv.Itoa(user.Id), 0, 4))
		o.QueryTable("GoodsSKU").Filter("Id__in", rep).All(&goods)
	}

	This.Data["goods"] = goods

	This.Layout = "UserCenterLayout.html"
	This.TplName = "user_center_info.html"
}

func (This *UserController) UserOrder() {
	userName := GetUser(This)
	println(userName)
	This.Layout = "UserCenterLayout.html"
	This.TplName = "user_center_order.html"
}

func (This *UserController) UserSite() {
	userName := GetUser(This)
	o := orm.NewOrm()

	var addr models.Address

	o.QueryTable("Address").RelatedSel("User").
		Filter("User__Name", userName).Filter("Isdefault", true).One(&addr)

	This.Data["addr"] = addr

	This.Layout = "UserCenterLayout.html"
	This.TplName = "user_center_site.html"
}

func (This *UserController) HandleUserSite() {
	receiver := This.GetString("receiver")
	addr := This.GetString("addr")
	zipCode := This.GetString("zipCode")
	phone := This.GetString("phone")
	if !torch.All(receiver, addr, zipCode, phone) {
		This.Ctx.WriteString("数据不完整")
		return
	}

	o := orm.NewOrm()

	var addrUser models.Address
	addrUser.Isdefault = true
	err := o.Read(&addrUser, "Isdefault")
	if err == nil {
		addrUser.Isdefault = false
		o.Update(&addrUser)
		This.Redirect("/user/UserSite", 302)
		return
		return
	}

	userName := This.GetSession("userName").(string)
	user := models.User{Name: userName}
	o.Read(&user, "Name")

	addrUserNew := models.Address{Receiver: receiver, Addr: addr,
		Zipcode: zipCode, Phone: phone, Isdefault: true, User: &user}
	o.Insert(&addrUserNew)
	This.Redirect("/user/UserSite", 302)
	return

}
